package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.getProperty
import groovy.json.JsonSlurper
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: HST_API_SftpFile_Chat_Msg
 * @Description: 华盛 企业微信读取（SFTP） 会话存档消息回传--内部接口
 * @author: join* @date 2021-07-24 16:00:00
 *
 */

public class HST_API_SftpFile_Chat_Msg implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(HST_API_SftpFile_Chat_Msg.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("utf-8");

        log.debug("-------------------------start HST_API_SftpFile_Chat_Msg 开始调用-----------------");
        log.debug("request请求----------------:" + request);


        String getMethod = request.getMethod();
        String callJson = "";
        BufferedReader iny = null;

        def reJson = "";
        def dataSourceID = "dataSource";

        log.debug("getMethod:" + getMethod);
        if (getMethod.equals("GET")) {
            callJson = request.getParameter("jsondata");
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                callJson += line;
            }
        }

        log.debug("callJson:" + callJson);
        try {

            // 调用处理信息手动参数
            JSONObject inObject = new JSONObject(callJson);
            log.debug("处理前的Json：" + inObject.toString());
            String hsttype = GetJV(inObject, "hsttype");//获取是否是手动调用 1001
            String datetime = GetJV(inObject, "datetime");//时间 20210723

            //获取配置参数
            String doURL = getProperty.get("HSTIP");//华盛通SFTPIP
            String HSTDEVHST = getProperty.get("HSTDEVHST");//华盛通SFTP用户名
            String HSTPWD = getProperty.get("HSTPWD");//华盛通SFTP密码
            String HSTPORT = getProperty.get("HSTPORT");//华盛通SFTP端口
            String HSTPATH = getProperty.get("HSTPATH");//华盛通SFTP文件路径
            //String HSTFINAME = getProperty.get("HSTFINAME");//华盛通SFTP文件名称 chat_msg_
            String LOACLPATH = getProperty.get("LOACLPATH");//存储下来的路径

            def getSelectSQL =	eliteBean.chaxun_sql("select  DATE_FORMAT(date_sub(curdate(),interval 1 day),'%Y%m%d') as nowtime,UUID() as  guid ","dataSource")
            String time2= getSelectSQL.get(0).get("nowtime");
            String guid= getSelectSQL.get(0).get("guid");
            log.debug("时间段=======：" + time2+"	guid:"+guid);
            /*
             String guid = UUID.randomUUID().toString();
             log.debug("时间段=======：" + time2+"	批次guid:"+guid);
             */

            //判断为job执行 还是1001手动执行
            if(hsttype=='1001'){
                time2=datetime;
            }

            //查询当天任务是否已经执行
            def batchguidresult = eliteBean.chaxun_sql("select guid as batchguid from hst_qw_batch_his where 1=1 and hst_type=3 and datetime='"+time2+"'", "dataSource");
            log.debug("batchguidresult=======：" + batchguidresult);

            def batchguid="";
            //存在则获取批次id
            if(batchguidresult.size()>0) {
                batchguid = batchguidresult.get(0).get("batchguid");
                log.debug("batchguid=======：" + batchguid);
                guid=batchguid;
            }
            log.debug("批次guid======="+guid);

            //企微文档 数据ok 判断是否上传成功
            String HSTPATHL1=HSTPATH+time2+"/chat_msg_"+time2+".ok";
            //企微文档 数据txt
            String HSTPATHL2=HSTPATH+time2+"/chat_msg_"+time2+".txt";
            log.debug("HSTPATH1=======：" + HSTPATHL1);
            log.debug("HSTPATH2=======：" + HSTPATHL2);

            LOACLPATH = LOACLPATH+"/chat_msg_"+time2+".txt";
            log.debug("存储下来的路径LOACLPATH============:" + LOACLPATH);

            Util util = new Util();
            def sftpresultok = util.downloadFileSftp(doURL, HSTDEVHST, HSTPWD, Integer.parseInt(HSTPORT), HSTPATHL1, LOACLPATH, 300000);
            log.debug("ok文件是否上传=======：" + sftpresultok);
            if(!sftpresultok){

                //hst_type 企微读取类型 1操作记录回传 2标签回传 3会话存档 4敏感词触发  state 0初始1执行
                //重复执行 则跟新当天的批次、否则新增批次任务
                if(batchguid==""||batchguid==null) {
                    eliteBean.update("insert into hst_qw_batch_his (guid,datetime,createddate,hst_type,state) values ('"+guid+"','"+time2+"',now(),3,0)", "dataSource");
                }else {
                    eliteBean.update("update  hst_qw_batch_his set modifydate=now(),state=0 where guid='"+batchguid+"'", "dataSource");
                }
                def reJoson = "{\"code\":\"0\",\"message\":\"失败，该批次还没有执行完毕\",\"data\":{}}";
                return reJoson;
            }
            //下载sftp文件，从数据库读取配置sftp和路径信息
            def sftpresult = util.downloadFileSftp(doURL, HSTDEVHST, HSTPWD, Integer.parseInt(HSTPORT), HSTPATHL2, LOACLPATH, 300000);
            log.debug("txt文件是否上传:" + sftpresult);
            //下载sftp文件，从数据库读取配置sftp和路径信息
            if (sftpresult) {
                log.debug("文件下载成功");
                File file = new File(LOACLPATH);
                //考虑到编码格式
                InputStreamReader read = new InputStreamReader(new FileInputStream(file.getAbsolutePath()), "UTF-8");

                //重复执行 则跟新当天的批次、否则新增批次任务
                if(batchguid==""||batchguid==null) {
                    eliteBean.update("insert into hst_qw_batch_his (guid,datetime,createddate,hst_type,state) values ('"+guid+"','"+time2+"',now(),3,1)", "dataSource");
                }else {
                    //数据处理
                    String[] data = new String[3];
                    data[0] ="update  hst_qw_batch_his set modifydate=now(),state=1 where guid='"+batchguid+"'";
                    data[1] ="delete from  hst_chat_msg where guid='"+batchguid+"'";
                    data[2] ="delete from  hst_chat_msg_receiver where guid='"+batchguid+"'";
                    def dataresult = eliteBean.updateBatch(data, "dataSource");
                    log.debug("SQL结果:" + dataresult.toString());
                }

                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                //逐行读取下载的文件
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    try {
                        log.debug("内容:" + lineTxt);
                        def columnJson = new JsonSlurper().parseText(lineTxt);
                        log.debug("columnJson:" + columnJson);
                        //保存规则ID
                        def msgtime = columnJson.msgtime;//消息发送时间戳
                        if(msgtime ==0 || msgtime==null){
                            msgtime="null";
                            //log.debug("进去了:=====" + msgtime);
                        }
                        log.debug("msgtime:=====" + msgtime);
                        def msgid = columnJson.msgid;//消息id
                        def tofrom = columnJson.from;//消息发送方id，当发送方是客户时，则是客户的华盛通ID;
                        def tolist = columnJson.tolist;//消息接收方列表，可能是多个，同一个企业内容为userid。数组，非相同企业为external_userid。内容为string类型。私聊时，当接收方是客户时，则是客户的华盛通ID; 群聊是为群ID；
                        if (tolist != "[]") {
                            tolist.each {
                                def receiver = it;
                                log.debug("receiver:" + receiver);

                                //查重
                                def receiverresult = eliteBean.chaxun_sql("select count(*) as count from hst_chat_msg_receiver where 1=1 and msgid='" + msgid + "' and  guid='"+guid+"' and receiver='"+receiver+"'", "dataSource");
                                log.debug("receiverresult=======：" + receiverresult);

                                def count;
                                if(receiverresult.size()>0) {
                                    count = receiverresult.get(0).get("count");
                                    log.debug("count=======：" + count);
                                    //如果存在则不处理，不存在则insert
                                    if(count>0){
                                        log.debug("已存在！"+receiver);
                                    }else{
                                        def trow1 = eliteBean.update("insert into hst_chat_msg_receiver (msgid,receiver,msgtime,guid) values ('" + msgid + "','" + receiver + "',FROM_UNIXTIME(" + msgtime + "/1000,'%Y-%m-%d %H:%i:%s'),'" +guid+"')", "dataSource");
                                        log.debug("trow1:" + trow1);

                                        if(receiver!=null){
                                            def updatecust1 = eliteBean.update("update customer set WeChat_Add_Status=2 where customer_id='" + receiver + "'", "dataSource");
                                            log.debug("updatecust1:" + updatecust1);
                                        }

                                    }
                                }
                            }
                        }

                        def roomid = columnJson.roomid;//群聊消息的群id。如果是单聊则为空
                        def msgtype = columnJson.msgtype;//文本消息类型
                        def action = columnJson.action;//消息动作， send发送消息
                        def details = columnJson.details;//消息具体内容
                        log.debug("details:" + details);

                        def content="";
                        if (details.size()>0&&msgtype=="text") {
                            JSONObject contentObject = new JSONObject(details);
                            content = GetJV(contentObject, "content");
                            log.debug("content:" + content);
                            //特殊字符处理
                            content=content.replace('\'',"");
                            log.debug("处理后的content:" + content);
                            /*
                            EmojiConverter emojiConverter = EmojiConverter.getInstance();
                            content= emojiConverter.toAlias(content);//将聊天内容进行转义
                             */

                        }else{
                            if(msgtype=="image"){
                                content="【图片，请前往企微后台查看】";
                            }else if(msgtype=="voice"){
                                content="【语音，请前往企微后台查看】";
                            }else if(msgtype=="video"){
                                content="【视频，请前往企微后台查看】";
                            }else if(msgtype=="card"){
                                content="【名片，请前往企微后台查看】";
                            }else if(msgtype=="location"){
                                content="【位置，请前往企微后台查看】";
                            }else if(msgtype=="emotion"){
                                content="【表情，请前往企微后台查看】";
                            }else if(msgtype=="file"){
                                content="【文件，请前往企微后台查看】";
                            }else if(msgtype=="link"){
                                content="【链接，请前往企微后台查看】";
                            }else if(msgtype=="weapp"){
                                content="【小程序消息，请前往企微后台查看】";
                            }else if(msgtype=="chatrecord"){
                                content="【会话记录消息，请前往企微后台查看】";
                            }else if(msgtype=="todo"){
                                content="【代办消息，请前往企微后台查看】";
                            }else if(msgtype=="vote"){
                                content="【投票消息，请前往企微后台查看】";
                            }else if(msgtype=="collect"){
                                content="【填表消息，请前往企微后台查看】";
                            }else if(msgtype=="redpacket"){
                                content="【红包消息，请前往企微后台查看】";
                            }else if(msgtype=="meeting"){
                                content="【会议邀请消息，请前往企微后台查看】";
                            }else if(msgtype=="docmsg"){
                                content="【在线文档消息，请前往企微后台查看】";
                            }else if(msgtype=="markdown"){
                                content="【MarKDown格式消息，请前往企微后台查看】";
                            }else if(msgtype=="news"){
                                content="【图文消息，请前往企微后台查看】";
                            }else if(msgtype=="calendar"){
                                content="【日程消息，请前往企微后台查看】";
                            }else if(msgtype=="mixed"){
                                content="【混合消息，请前往企微后台查看】";
                            }else if(msgtype=="meeting_voice_call"){
                                content="【音频存档消息，请前往企微后台查看】";
                            }
                        }
                        /*
                        def trow = eliteBean.update("insert into hst_chat_msg (msgid,tofrom,tolist,roomid,msgtime,msgtype,action,details,guid) values ('" + msgid + "','" + tofrom + "','','" + roomid + "',FROM_UNIXTIME(" + msgtime + "/1000,'%Y-%m-%d %H:%i:%s'),'" + msgtype + "','" + action + "','" + content + "','"+guid+"')", "dataSource");
                        log.debug("trow:" + trow);
                         */

                        //查询当前是否存在
                        def hst_chat_msgresult = eliteBean.chaxun_sql("select msgid from hst_chat_msg where 1=1 and msgid='" + msgid + "' limit 1", "dataSource");
                        log.debug("hst_chat_msgresult=======：" + hst_chat_msgresult);
                        def oldmsgid;
                        //如存在 则不记录
                        if(hst_chat_msgresult.size()>0){
                            oldmsgid = hst_chat_msgresult.get(0).get("msgid");
                            log.debug("oldmsgid=======：" + oldmsgid);
                        }else{//标签不存在则新增
                            //数据处理
                            String[] data = new String[2];
                            data[0] ="set names utf8mb4";
                            data[1] ="insert into hst_chat_msg (msgid,tofrom,tolist,roomid,msgtime,msgtype,action,details,guid) values ('" + msgid + "','" + tofrom + "','','" + roomid + "',FROM_UNIXTIME(" + msgtime + "/1000,'%Y-%m-%d %H:%i:%s'),'" + msgtype + "','" + action + "','" + content + "','"+guid+"')";
                            def dataresult = eliteBean.updateBatch(data, "dataSource");
                            log.debug("SQL结果:" + dataresult.toString());
                        }
                        if(tofrom!=null){
                            //def updatecust2 = eliteBean.update("update customer set WeChat_Add_Status=2 where customer_id='" + tofrom + "'", "dataSource");
                            def updatecust2 = eliteBean.update("update customer set WeChat_Add_Status=2,latestbehaviortype=case when latestbehaviortime is null then 4 when latestbehaviortime<FROM_UNIXTIME(" + msgtime + "/1000,'%Y-%m-%d %H:%i:%s') then 4 else latestbehaviortype end,wecomtime= case when wecomtime is null then FROM_UNIXTIME(" + msgtime + "/1000,'%Y-%m-%d %H:%i:%s') when wecomtime<FROM_UNIXTIME(" + msgtime + "/1000,'%Y-%m-%d %H:%i:%s') then FROM_UNIXTIME(" + msgtime + "/1000,'%Y-%m-%d %H:%i:%s') else wecomtime end,latestbehaviortime=case when latestbehaviortime is null then FROM_UNIXTIME(" + msgtime + "/1000,'%Y-%m-%d %H:%i:%s') when latestbehaviortime<FROM_UNIXTIME(" + msgtime + "/1000,'%Y-%m-%d %H:%i:%s') then FROM_UNIXTIME(" + msgtime + "/1000,'%Y-%m-%d %H:%i:%s') else latestbehaviortime end  where customer_id='" + tofrom + "'", "dataSource");

                            log.debug("updatecust2:" + updatecust2);
                        }

                    } catch (Exception e) {
                        log.error(Util.getERRO(e));
                    }
                }
                //读取完成，关闭并删除临时文件
                read.close();
                file.delete();
                def reJoson = "{\"code\":\"1\",\"message\":\"成功\",\"data\":{}}";
                log.debug("返回Json:" + reJoson);


                log.debug("start HST_API_SftpFile_Chat_Msg结束执行任务--------------------------");
                return reJoson;
            }
        } catch (Exception e) {
            log.error("ErrorMessage", e);
            reJson = "{\"Code\":\"-1\",\"Message\":\"错误:" + e.getMessage() + "\",\"data\":null}";
            log.debug("处理异常返回Json:" + reJson);
            return reJson;
        }


    }
    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }
}